package org.htzb.news.dao.impl;

import org.htzb.news.dao.C3P0Util;
import org.htzb.news.dao.CommentDao;
import org.htzb.news.entity.Comment;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CommentDaoImpl extends C3P0Util implements CommentDao {

    @Override
    public List<Comment> getCommentsByNid(int nid) throws SQLException {
        String sql = "select * from comments where cnid =" + nid;
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        List<Comment> commentList = new ArrayList<Comment>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (resultSet.next()) {
            int cid = resultSet.getInt("CID");
            int cnid = resultSet.getInt("CNID");
            String ccontent = resultSet.getString("CCONTENT");
            String cauthor = resultSet.getString("CAUTHOR");
            Timestamp cdate = resultSet.getTimestamp("CDATE");
            String cdateStr = null;
            if (cdate != null) {
                cdateStr = dateFormat.format(cdate);
            }
            String cip = resultSet.getString("CIP");


            Comment comment = new Comment();
            comment.setCid(cid);
            comment.setCnid(cnid);
            comment.setCcontent(ccontent);
            comment.setCdate(cdateStr);
            comment.setCip(cip);
            comment.setCauthor(cauthor);
            commentList.add(comment);
        }
        return commentList;
    }

    @Override
    public void addComment(Comment comment) throws SQLException {
        String sql="INSERT INTO comments(CNID,CCONTENT,CDATE,CIP,CAUTHOR) value(?,?,?,?,?)";
        Connection connection=getConnection();
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setInt(1, comment.getCnid());
        preparedStatement.setString(2, comment.getCcontent());
        preparedStatement.setString(3, comment.getCdate());
        preparedStatement.setString(4, comment.getCip());
        preparedStatement.setString(5, comment.getCauthor());
        preparedStatement.executeUpdate();
    }

    public static void main (String[] args) throws SQLException {
            CommentDao commentDao = new CommentDaoImpl();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            commentDao.addComment(new Comment(170,"评论点什么呢",simpleDateFormat.format(new Date()),"127.0.0.1","康辉"));
//            List<Comment> commentsList = commentDao.getCommentsByNid(170);
//            System.out.println("总共有" + commentsList.size() + "条评论信息");
//            for (Comment comment : commentsList) {
//                System.out.println(comment);
//            }

        }
}
